﻿var newBakModel = new Object();
var rowid;

$(document).ready(function () {
    //контексное меню
    var contextMenu = $("#Menu").jqxMenu({ width: 120, height: 86, theme:theme, autoOpenPopup: false, mode: 'popup' });
    $("#jTable").bind('contextmenu', function () {
        return false;
    });

    // handle context menu clicks.
    $("#Menu").bind('itemclick', function (event) {
        var args = event.args;
        var rowindex = $("#jTable").jqxGrid('getselectedrowindex');
        rowid = $("#jTable").jqxGrid('getrowid', rowindex);
        if (args.id == "edit") {
            $.ajax({
                url: '/data/bak/',
                data: { id: rowid },
                type: "GET",
                contentType: 'application/json; charset=utf-8',
                success: function (data) {
                    newBakModel.Id = data.Id;

                    newBakModel.Date = data.Date;
                    newBakModel.SerialNumber = data.SerialNumber;
                    newBakModel.Creator = data.Creator;
                    newBakModel.Type = data.TypeId;
                    newBakModel.Expluat = data.ExpluatId;
                    $('#jqxWindow').jqxWindow('setTitle', 'Редактирование');
                    $("#jqxWindow").jqxWindow('show');

                    var dropDownContent = '<div style="position: relative; margin-left: 3px; margin-top: 5px;">' + data.Type + '</div>';
                    $("#bakType").jqxDropDownButton('setContent', dropDownContent);

                    dropDownContent = '<div style="position: relative; margin-left: 3px; margin-top: 5px;">' + data.Expluat + '</div>';
                    $("#expOrg").jqxDropDownButton('setContent', dropDownContent);


                },
                error: function (data) {
                    alert(data.responseText);
                }
            });

        }
        else if (args.id == "add") {
            newBakModel.Id = null;
            newBakModel.SerialNumber = null;
            newBakModel.Date = new Date();
            $('#jqxWindow').jqxWindow('setTitle', 'Добавить новую запись');
            $('#jqxWindow').jqxWindow('open');
        } else {
            $("#jqxWindow").jqxWindow('close');
            $('#deleteWindow').jqxWindow('open');
        }
        $("#Menu").jqxMenu('close');
    });
    $("#jTable").bind('rowclick', function (event) {
        if (event.args.rightclick) {
            $("#jTable").jqxGrid('selectrow', event.args.rowindex);
            var scrollTop = $(window).scrollTop();
            var scrollLeft = $(window).scrollLeft();
            contextMenu.jqxMenu('open', parseInt(event.args.originalEvent.clientX) + 5 + scrollLeft, parseInt(event.args.originalEvent.clientY) + 5 + scrollTop);
            return false;
        }
    });
    
    //создается окно на добавление/редактирование
    
    $('#jqxWindow').jqxWindow({
        height: 420,
        width: 320,
        theme: theme,
        autoOpen: false,
        resizable: false,
        animationType: 'none',
        showCloseButton: false,
        cancelButton: $('#CancelButton'),
        initContent: function () {
            $('#SubmitButton').jqxButton({ width: '100px', theme: theme, heigh: 50 });
            $('#CancelButton').jqxButton({ width: '100px', theme: theme, heigh: 50 });
            
            $("#creator").jqxInput({ placeHolder: "изготовитель", height: 25, width: '100%', minLength: 1, theme: theme });

            $("#serialNumber").jqxMaskedInput({ width: "100%", height: 30, theme: theme, mask: '###-####-####-####', textAlign: "center", value: newBakModel.SerialNumber });
            $('#creator').val(newBakModel.Creator);
            $('#dateOfCreate').jqxDateTimeInput('setDate', new Date(newBakModel.Date));
        }
    });

    //кнопка биндинга для добавления
    $('#addButtom').jqxButton({ width: '100px', theme: theme, heigh: 50 });
    $('#addButtom').bind('click', function () {
        newBakModel.Date = new Date();
        $('#jqxWindow').jqxWindow('open');
    });


    //кнопка биндинга для подтверждения
    $('#SubmitButton').jqxButton({ width: '100px', theme: theme, heigh: 50 });
    $('#SubmitButton').bind('click', function () {
        $('#BakConfig').jqxValidator('validate');
    });

    
    $('#CancelButton').jqxButton({ width: '100px', theme: theme, heigh: 50 });
    $("#dateOfCreate").jqxDateTimeInput({
        width: '100%',
        height: 30,
        culture: 'ru-RU',
        theme: theme,
        textAlign: "center",
        maxDate: new $.jqx._jqxDateTimeInput.getDateTime(new Date())
    });
    
    //создаем окно для диалога удаления
    $('#deleteWindow').jqxWindow({
        width: 400,
        height: 120,
        resizable: false, theme: theme,
        isModal: true,
        autoOpen: false,
        cancelButton: $('#cancelButton'),
        okButton: $('#okButton'),
        initContent: function () {
            $('#cancelButton').jqxButton({ width: '100px', theme: theme, heigh: 50 });
            $('#okButton').jqxButton({ width: '100px', theme: theme, heigh: 50 });
            $('#deleteWindow').jqxWindow({ title: ("Удаление БАК-а") });
        }
    });

    //биндим кнопку удаления
    $("#okButton").bind('click', function () {
        $.ajax({
            url: '/data/bak/' + rowid,
            type: "DELETE",
            success: function () {
                $('#jTable').jqxGrid('updatebounddata');
            },
            error: function (data) {
                alert(data.responseText);
            }
        });
    });
   
    //создаем модуль валидации
    $('#BakConfig').jqxValidator({
        rules: [
            { input: '#serialNumber', message: 'Серийный номер не указан!', action: 'keyup, blur, mousemove', rule: 'required' },
            {
                input: '#bakType',
                message: 'Выберите тип!',
                action: 'keyup, blur, mouseover',
                rule: function () {
                    return newBakModel.Type != null;
                }
            },
            { input: '#creator', message: 'Изготовитель не указан!', action: 'keyup, blur, mousemove', rule: 'required' },
            {
                input: '#expOrg',
                message: 'Выберите эксплуатирующую организацию!',
                action: 'keyup, blur, mouseover',
                rule: function () {
                    return newBakModel.Expluat != null;
                }
            }
        ], theme: theme,
        onSuccess: function () {
            newBakModel.SerialNumber = $('#serialNumber').jqxMaskedInput('val').replace(/-/g, '');
            newBakModel.Creator = $("#creator").val();
            newBakModel.Date = $("#dateOfCreate").jqxDateTimeInput('getDate');

            $.ajax({
                url: '/data/bak',
                type: 'PUT',
                data: JSON.stringify(newBakModel),
                dataType: 'json',
                contentType: 'application/json; charset=utf-8',
                success: function () {
                    $('#jTable').jqxGrid('updatebounddata');
                    $('#jqxWindow').jqxWindow('close');
                },
                error: function (data) {
                    alert(data.responseText);
                }
            });
        }
    });
   
    //запросы создания деревьев в диалоговых окнах
    $.ajax({
        url: '/data/Classificator/40000000000',
        type: "GET",
        contentType: 'application/json; charset=utf-8',
        success: function (data) {
            $("#bakTypeTree").jqxTree({
                width: 300, theme: theme,
                source: data
            });
        },
        error: function () {
            alert('Невозможно подключиться к серверу данных.');
        }
    });

    $.ajax({
        url: '/data/Classificator/10020000000',
        type: "GET",
        contentType: 'application/json; charset=utf-8',
        success: function (data) {
            $("#expOrgTree").jqxTree({
                width: 300, theme: theme,
                source: data
            });
        },
        error: function () {
            alert('Невозможно подключиться к серверу данных.');
        }
    });
    
    //фильтр 1 для Type
    $('#bakTypeTree').bind('expand', function (event) {
        var $element = $(event.args.element);
        var loader = false;
        var loaderItem = null;
        var children = $element.find('li');
        $.each(children, function () {
            var item = $('#bakTypeTree').jqxTree('getItem', this);
            if (item.label == 'Loading...') {
                loaderItem = item;
                loader = true;
                return false;
            }
            ;
        });
        if (loader) {
            $.ajax({
                url: '/data/Classificator',
                data: { id: loaderItem.value },
                contentType: 'application/json; charset=utf-8',
                success: function (data, status, xhr) {
                    if (data.length > 0) {
                        $('#bakTypeTree').jqxTree('addTo', data, $element[0]);
                        $('#bakTypeTree').jqxTree('removeItem', loaderItem.element);
                    } else {
                        $('#bakTypeTree').jqxTree('removeItem', loaderItem.element);
                    }
                },
                error: function () {
                    alert("Не удалось подключиться к серверу");
                }
            });
        }
    });
    $("#bakType").jqxDropDownButton({ width: '100%', theme: theme, height: 25 });
    $('#bakTypeTree').bind('select', function (event) {
        var args = event.args;
        var item = $('#bakTypeTree').jqxTree('getItem', args.element);
        if (item.hasItems == false) {
            var dropDownContent = '<div style="position: relative; margin-left: 3px; margin-top: 5px;">' + item.label + '</div>';
            newBakModel.Type = item.id;
            $("#bakType").jqxDropDownButton('setContent', dropDownContent);
        }
    });
    //фильтр 2 для Expluat
    $('#expOrgTree').bind('expand', function (event) {
        var $element = $(event.args.element);
        var loader = false;
        var loaderItem = null;
        var children = $element.find('li');
        $.each(children, function () {
            var item = $('#expOrgTree').jqxTree('getItem', this);
            if (item.label == 'Loading...') {
                loaderItem = item;
                loader = true;
                return false;
            }
            ;
        });
        if (loader) {
            $.ajax({
                url: '/data/Classificator',
                data: { id: loaderItem.value },
                contentType: 'application/json; charset=utf-8',
                success: function (data, status, xhr) {
                    if (data.length > 0) {
                        $('#expOrgTree').jqxTree('addTo', data, $element[0]);
                        $('#expOrgTree').jqxTree('removeItem', loaderItem.element);
                    } else {
                        $('#expOrgTree').jqxTree('removeItem', loaderItem.element);
                    }
                },
                error: function () {
                    alert("Не удалось подключиться к серверу");
                }
            });
        }
    });
    $("#expOrg").jqxDropDownButton({ width: '100%', theme: theme, height: 25 });
    $('#expOrgTree').bind('select', function (event) {
        var args = event.args;
        var item = $('#expOrgTree').jqxTree('getItem', args.element);
        if (item.hasItems == false) {
            var dropDownContent = '<div style="position: relative; margin-left: 3px; margin-top: 5px;">' + item.label + '</div>';
            newBakModel.Expluat = item.id;
            $("#expOrg").jqxDropDownButton('setContent', dropDownContent);
        }
    });
   
    // prepare the data для таблицы
    var source =
        {
            datatype: "json",
            datafields: [
                { name: 'Id' },
                { name: 'SerialNumber' },
                { name: 'Type' },
                { name: 'Creator' },
                { name: 'Expluat' },
                { name: 'Date', type: 'date' }
            ],
            url: '/data/bak',
            root: 'Rows',
            id: "Id",
            beforeprocessing: function (data) {
                source.totalrecords = data.TotalRows;
            }
        }; 
    var dataadapter = new $.jqx.dataAdapter(source);
    // initialize таблицы
    $("#jTable").jqxGrid(
        {
            width: "99%",
            source: dataadapter,
            autoheight: true,
            pageable: true,
            virtualmode: true, theme: theme,
            pagesizeoptions: ['10', '20', '30'],
            enabletooltips: true,
            rendergridrows: function () {
                return dataadapter.records;
            },
            columns: [
                { text: 'Серийный номер', datafield: 'SerialNumber' },
                { text: 'Тип БАК-а', datafield: 'Type' },
                { text: 'Изготовитель', datafield: 'Creator' },
                { text: 'Эксплуатирующая организация', datafield: 'Expluat' },
                { text: 'Время', datafield: 'Date', cellsformat: "dd.MM.yyyy" }
            ]
        }); 
});